package com.uenpay.im.ui.old.activity.crowdfund;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qyx.android.message.type.PacketType;
import com.qyx.android.weight.view.MyListView;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.pwd.SetPayPwdActivity;
import com.uenpay.im.ui.old.activity.wallet.ChargeActivity;
import com.uenpay.im.ui.old.activity.wallet.WalletHandle;
import com.uenpay.im.callback.IOnBottomDialogListener;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.utilities.QyxDateUtils;
import com.uenpay.im.weight.DialogUtility;
import com.uenpay.im.weight.PayPwdDialog;
import com.uenpay.im.weight.RoundImageView;
import com.uenpay.util.app.base.BaseActivity;

import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

/**
 * @author SL
 * @version 1.0
 * @copyRight http://www.qiyunxin.com
 * @E-mail:
 * @date 创建时间：2016-5-7 下午4:23:41
 * @function 众筹(江湖救急)详情
 */
public class CrowdFundDetailActivity extends BaseActivity {

    private EditText pay_et;
    private Button pay_btn;
    private TextView pay_detail_tv, received_name, create_date,
            crowdfund_memo_tv, no_pay_tv;
    private LinearLayout pay_detail_layout, crowdfund_bottom_layout;
    private MyListView pay_list;
    private ImageView complete_iv;
    private RoundImageView avatar;
    private View loading;
    private String myBalance;
    private int haspaypassword;
    private String fundid;
    private CFRecordAdapter cfRecordAdapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_crowdfund_detail_layout;
    }

    @Override
    public void initView(View view) {
        fundid = getIntent().getStringExtra("fundid");
        getBalance();
        initView();
        initListener();
        getCrowdFundDetail(fundid);
    }

    protected void initView() {
        ((TextView) findViewById(R.id.title_textview))
                .setText(R.string.crowdfund_detail);
        pay_btn = (Button) findViewById(R.id.pay_btn);
        pay_et = (EditText) findViewById(R.id.pay_et);
        pay_detail_tv = (TextView) findViewById(R.id.pay_detail_tv);
        received_name = (TextView) findViewById(R.id.received_name);
        create_date = (TextView) findViewById(R.id.create_date);
        no_pay_tv = (TextView) findViewById(R.id.no_pay_tv);
        crowdfund_memo_tv = (TextView) findViewById(R.id.crowdfund_memo_tv);
        crowdfund_bottom_layout = (LinearLayout) findViewById(R.id.crowdfund_bottom_layout);
        complete_iv = (ImageView) findViewById(R.id.complete_iv);
        pay_detail_layout = (LinearLayout) findViewById(R.id.pay_detail_layout);
        pay_list = (MyListView) findViewById(R.id.pay_list);
        loading = findViewById(R.id.loading);
        avatar = (RoundImageView) findViewById(R.id.avatar);
    }

    protected void initListener() {
        pay_et.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
                checkBtnStatus();
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {
            }

            @Override
            public void afterTextChanged(Editable arg0) {
            }
        });
        pay_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                String amount = pay_et.getText().toString();
                if (!TextUtils.isEmpty(amount)) {
                    try {
                        if (!TextUtils.isEmpty(myBalance)) {
                            double tempBalance = Double.valueOf(myBalance);
                            double tempAmount = Double.valueOf(amount);
                            if (tempAmount > tempBalance) {
                                // TODO
                                showInsufficientBalanceDialog();
                            } else {
                                if (haspaypassword == 1) {
                                    showPayPwdDialog(amount);
                                } else {
                                    //sosTransfer("", amount);
                                    showSetPwdDialog();
                                }
                            }
                        }
                    } catch (Exception e) {
                    }
                }
            }
        });
    }

    private void checkBtnStatus() {
        String money = pay_et.getText().toString();
        if (!TextUtils.isEmpty(money)) {
            pay_btn.setEnabled(true);
            pay_btn.setBackgroundResource(R.drawable.button_bg_normal);
        } else {
            pay_btn.setBackgroundResource(R.drawable.button_bg_gray);
            pay_btn.setEnabled(false);
        }
    }

    /**
     * 余额不足提示
     */
    private void showInsufficientBalanceDialog() {
        loading.setVisibility(View.GONE);
        DialogUtility.showDialog(CrowdFundDetailActivity.this,
                R.string.insufficient_balance, R.string.sure, R.string.cancel,
                true, new IOnBottomDialogListener() {

                    @Override
                    public void onClicked() {
                        Intent intent = new Intent(
                                CrowdFundDetailActivity.this,
                                ChargeActivity.class);
                        startActivityForResult(intent, 100);
                    }
                });
    }

    /**
     * 支付密码提示框
     *
     * @param amount
     */
    private void showPayPwdDialog(final String amount) {
        PayPwdDialog.showBottomRedDialog(CrowdFundDetailActivity.this,
                new PayPwdDialog.IPayPwdInputFinishListener() {

                    @Override
                    public void onPayPwdInputFinish(String payPwd) {
                        sosTransfer(payPwd, amount);
                    }
                });
    }

    /**
     * 获取详情
     *
     * @param fundid
     */
    private void getCrowdFundDetail(String fundid) {
        loading.setVisibility(View.VISIBLE);
        CrowdFundHandle.getCrowdFundDetail(fundid,
                new CrowdFundHandle.IGetCrowdFundDetailListener() {

                    @Override
                    public void onGetCrowdFundDetailResult(
                            GetCrowdfundInfoInvokItem.GetCrowdfundInfoInvokItemResult result) {
                        loading.setVisibility(View.GONE);
                        if (result != null) {
                            if (result.status == HttpInvokeResultCode.RESULT_OK) {

                                if (result != null) {
                                    if (result.custid.equals(IMApplication
                                            .getCustId())) {
                                        crowdfund_bottom_layout
                                                .setVisibility(View.GONE);
                                        received_name.setText(R.string.me);
                                    } else {
                                        crowdfund_bottom_layout
                                                .setVisibility(View.VISIBLE);
                                        received_name.setText(result.nickname);
                                    }

                                    if (TextUtils.isEmpty(result.memo)) {
                                        result.memo = getResources().getString(R.string.crowdfund_memo);
                                    }

                                    crowdfund_memo_tv.setText(result.memo
                                            + "\n"
                                            + MessageFormat
                                            .format(getResources()
                                                            .getString(
                                                                    R.string.target_amount),
                                                    result.amount));
                                    renderingTv(result.amount);


                                    avatar.SetUrl(APIConfiguration
                                            .getAvatarUrlNormal(result.custid,
                                                    PacketType.PERSONAL));
                                    /** 收齐 **/
                                    if (result.sosstatus == 1) {
                                        crowdfund_bottom_layout
                                                .setVisibility(View.GONE);
                                        complete_iv.setVisibility(View.VISIBLE);
                                    } else {
                                        if (!result.custid
                                                .equals(IMApplication
                                                        .getCustId())) {
                                            crowdfund_bottom_layout
                                                    .setVisibility(View.VISIBLE);
                                        }
                                        complete_iv.setVisibility(View.GONE);
                                    }
                                }
                                if (result.arrayList != null
                                        && result.arrayList.size() > 0) {
                                    setCrowdFundTotal(result.arrayList);
                                    cfRecordAdapter = new CFRecordAdapter(
                                            CrowdFundDetailActivity.this,
                                            result.arrayList);
                                    pay_list.setAdapter(cfRecordAdapter);
                                    no_pay_tv.setVisibility(View.GONE);
                                    pay_detail_layout
                                            .setVisibility(View.VISIBLE);
                                } else {
                                    no_pay_tv.setVisibility(View.VISIBLE);
                                    pay_detail_layout.setVisibility(View.GONE);
                                }

                                SimpleDateFormat sdf = new SimpleDateFormat(
                                        "yyyy-MM-dd HH:mm:ss", Locale
                                        .getDefault());
                                try {
                                    long millionSeconds = sdf.parse(result.createtime).getTime();
                                    String time = QyxDateUtils.generateDateTimeString(new Date(
                                            millionSeconds));
                                    create_date.setText(time);
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                                //create_date.setText(result.createtime);
                            } else if (!TextUtils.isEmpty(result.msg)) {
                                IMApplication.showToast(result.msg);
                            }
                        }
                        findViewById(R.id.scroll_view).setVisibility(View.VISIBLE);
                    }
                });
    }

    private void setCrowdFundTotal(ArrayList<CFRecordEntity> arrayList) {
        int color = Color.argb(255, 2, 150, 209);
        ForegroundColorSpan normalSpan = new ForegroundColorSpan(color);
        double total = 0;
        for (int i = 0, size = arrayList.size(); i < size; i++) {
            double temp = Double.valueOf(arrayList.get(i).amount);
            total += temp;
        }

        pay_detail_tv.setText(MessageFormat.format(
                getResources().getString(R.string.crowdfund_total_amount),
                arrayList.size(), total));
        String count = arrayList.size() + "";
        int len = pay_detail_tv.getText().toString().length() - 1;
        SpannableStringBuilder builder = new SpannableStringBuilder(
                pay_detail_tv.getText().toString());
        builder.setSpan(normalSpan, 7 + count.length(), len,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        pay_detail_tv.setText(builder);

    }

    private void renderingTv(String amount) {
        int color = Color.argb(255, 141, 141, 141);
        ForegroundColorSpan normalSpan = new ForegroundColorSpan(color);
        SpannableStringBuilder builder = new SpannableStringBuilder(
                crowdfund_memo_tv.getText().toString());
        int len = crowdfund_memo_tv.getText().toString().length();
        int amountLen = amount.toString().length() + 5;
        builder.setSpan(normalSpan, len - amountLen, len,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        crowdfund_memo_tv.setText(builder);
    }

    private void showSetPwdDialog() {
        DialogUtility.showDialog(CrowdFundDetailActivity.this,
                R.string.not_set_pay_pwd, R.string.sure, R.string.cancel, true,
                new IOnBottomDialogListener() {

                    @Override
                    public void onClicked() {
                        Intent intent = new Intent(
                                CrowdFundDetailActivity.this,
                                SetPayPwdActivity.class);
                        startActivity(intent);
                        finish();
                    }
                });
    }

    /**
     * 转账
     *
     * @param paypassword
     * @param amount
     */
    private void sosTransfer(String paypassword, String amount) {
        loading.setVisibility(View.VISIBLE);
        CrowdFundHandle.sosTransfer(fundid, paypassword, amount, "",
                new CrowdFundHandle.ISosTransferListener() {

                    @Override
                    public void onSosTransferResult(int status, String msg) {
                        loading.setVisibility(View.GONE);
                        if (status == HttpInvokeResultCode.RESULT_OK) {
                            getCrowdFundDetail(fundid);
                            pay_et.setText("");
                            pay_btn.setBackgroundResource(R.drawable.button_bg_gray);
                            pay_btn.setEnabled(false);
                        } else if (status == 2610) {
                            IMApplication.showToast(R.string.pay_pwd_error);
                        } else if (!TextUtils.isEmpty(msg)) {
                            IMApplication.showToast(msg);
                        }
                    }
                });
    }

    /**
     * 获取余额
     */
    private void getBalance() {
        WalletHandle.getBalance(new WalletHandle.IGetBalanceResultListener() {

            @Override
            public void onGetBalanceResult(String balance, int status,
                                           int _haspaypassword) {
                if (status == HttpInvokeResultCode.RESULT_OK) {
                    myBalance = balance;
                    haspaypassword = _haspaypassword;
                }
            }
        });

    }

    @Override
    public void onBackPressed() {
        finish();
        super.onBackPressed();
    }
}
